//
//  DBOperation.m
//  IconMaster
//
//  Created by nhn on 14-9-5.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "DBOperation.h"
#import "DBUtil.h"
#import "Util.h"
#import "CImageUtil.h"
#import <objc/runtime.h>
#import "JSONKit.h"
#import "NetworkAPI.h"
#import "SDWebImageManager.h"

#define IMAGE_CACHE_THREAD_SAFE		1
#define DEFAULT_URL     @"http://www.yyqzz.com"
//#define DEFAULT_URL     @"http://192.168.0.102"

static char id_key;
static NSMutableDictionary* imageCacheDict = nil;

@implementation DBOperation

+ (NSMutableArray *)iconGroupArray
{
    NSMutableArray* array = [self groupArryForTableViewWithType:@"icon"];
    NSDictionary* presetDict = nil;
    for (NSDictionary* dict in array) {
        NSString* title = [dict objectForKey:GROUP_KEY_TITLE];
        if ([title isEqualToString:@"preset"] || [title isEqualToString:@"内置"]) {
            presetDict = dict;
            break;
        }
    }
    if (presetDict) {
        [array removeObject:presetDict];
    }
    return array;
}

+ (NSMutableArray *)skinGroupArray
{
	NSMutableArray* array = [self groupArryForTableViewWithType:@"skin"];
	return array;
}

+ (NSMutableArray *)frameGroupArray
{
	NSMutableArray* array = [self groupArryForTableViewWithType:@"frame"];
	return array;
}

+ (NSMutableArray *)decoGroupArray
{
	NSMutableArray* array = [self groupArryForTableViewWithType:@"deco"];
	return array;
}


+ (NSMutableArray*)groupArryForTableViewWithType:(NSString*)type
{
	NSMutableArray* array = [NSMutableArray array];
	NSArray* groupArray = [self groupArrayWithType:type];
	
	for (NSDictionary* dict in groupArray) {
		NSMutableDictionary* groupDict = [NSMutableDictionary dictionary];
	
        if ([self getLocalizedGroupNameFromDict:dict]) {
            [groupDict setObject:[self getLocalizedGroupNameFromDict:dict] forKey:GROUP_KEY_TITLE];
        }
        if ([dict objectForKey:@"deletable"]) {
            [groupDict setObject:[dict objectForKey:@"deletable"] forKey:GROUP_KEY_DELETE];
        }
		if ([dict objectForKey:@"id"]) {
			[groupDict setObject:[dict objectForKey:@"id"] forKey:GROUP_KEY_ID];
		}
        if ([dict objectForKey:@"downloaded"]) {
			[groupDict setObject:[dict objectForKey:@"downloaded"] forKey:GROUP_KEY_DOWNLOAD];
        }
        if ([dict objectForKey:@"globalpath"]) {
			[groupDict setObject:[dict objectForKey:@"globalpath"] forKey:GROUP_KEY_GLOBALPATH];
        }
        
		[array addObject:groupDict];
	}
	
	return array;
}

+ (NSString*)savedIconPath
{
	static BOOL directoryCheck = YES;
    NSString* path = [DocumentDirectory() stringByAppendingPathComponent:@"SavedIcon"];
	
	if (directoryCheck) {
		directoryCheck = NO;
		
		if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
			[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
		}
	}
	
    return path;
}

+ (NSArray *)savedIconArray
{
    NSArray* iconArray;
    iconArray = [DBUtil query:@"select * from saved"];
    return iconArray;
}

+ (NSArray *)savedIconArrayStartIndex:(int)start count:(int)count
{
    NSArray* iconArray;
    iconArray = [DBUtil query:@"select * from saved limit %d, %d", start, count];
    return iconArray;
}

+ (void)deleteSavedIconWithID:(int)iconID
{
	NSArray* result = [DBUtil query:@"select * from saved where id=%d", iconID];
	if (result.count) {
		NSDictionary* dict = [result objectAtIndex:0];
		NSString* dataPath = [[self savedIconPath] stringByAppendingPathComponent:[dict objectForKey:@"datapath"]];
		NSString* imagePath = [[self savedIconPath] stringByAppendingPathComponent:[dict objectForKey:@"imagepath"]];
		[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
		[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
	}
	
    [DBUtil update:@"delete from saved where id=%d", iconID];
}

+ (int)insertSavedIconWithIconImage:(UIImage*)image {
	if (!image) {
		return -1;
	}
	
    CIconView* iconView = nil;
    iconView = [CIconView iconViewFromNibWithCornorRadius];
    [iconView setBackgroundImage:image];
    
    return [self insertSavedIconWithIconView:iconView];
}

+ (int)insertSavedIconWithIconView:(CIconView *)iconView
{
    NSString* dataFileName = [[NSUUID UUID] UUIDString];
    NSString* dataPath = [[self savedIconPath] stringByAppendingPathComponent:dataFileName];
	NSString* previewImageFileName = [dataFileName stringByAppendingString:@".png"];
    NSString* imagePath = [[self savedIconPath] stringByAppendingPathComponent:previewImageFileName];
    
	BOOL succeed = false;
	succeed = [NSKeyedArchiver archiveRootObject:iconView toFile:dataPath];
	UIImage* previewImage = [CImageUtil imageFromView:iconView];
	succeed = [UIImagePNGRepresentation(previewImage) writeToFile:imagePath atomically:YES];
    
    [DBUtil update:@"insert into saved values(NULL, %@, %@)", dataFileName, previewImageFileName];
    
    int lastID = -1;
    NSArray* result = [DBUtil query:@"select max(id) as mid from saved"];
    if (result.count) {
        NSDictionary* dict = [result objectAtIndex:0];
        lastID = (int)[[dict objectForKey:@"mid"] integerValue];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_ADD_SAVED_ICON object:nil];
    
    return lastID;
}

+ (CIconView *)getIconViewFromSavedIconWithID:(int)iconID
{
    CIconView* iconView = NULL;
    NSArray* result = [DBUtil query:@"select * from saved where id=%d", iconID];
    if (result.count) {
		iconView = [self getIconViewForSavedIconDict:[result objectAtIndex:0]];
    }
    return iconView;
}

+ (UIImage*)getImageForSavedIconDict:(NSDictionary*)iconDict {
	UIImage* image = nil;
	NSString* dataPath = [[self savedIconPath] stringByAppendingPathComponent:[iconDict objectForKey:@"imagepath"]];
	image = [UIImage imageWithContentsOfFile:dataPath];
	
	return image;
}

+ (CIconView*)getIconViewForSavedIconDict:(NSDictionary*)iconDict {
    CIconView* iconView = NULL;
    if (iconDict) {
		NSString* dataPath = [[self savedIconPath] stringByAppendingPathComponent:[iconDict objectForKey:@"datapath"]];
        iconView = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
    }
    return iconView;
}

+ (NSDictionary*)groupDictWithGroupID:(int)groupID {
	NSDictionary* groupDict = nil;
	
	NSArray* result = [DBUtil query:@"select * from grp where id = %d", groupID];
	if (result && result.count) {
		groupDict = [result objectAtIndex:0];
	}
	
	return groupDict;
}

+ (NSArray *)groupArrayWithType:(NSString *)type
{
    NSArray* array = [DBUtil query:@"select * from grp where type like %@", type];
    return array;
}

+ (NSArray*)imageArrayForGroupID:(int)groupID
{
    NSArray* array = nil;
    if (groupID == GROUP_KEY_SAVEDICON_ID) {
        array = [self savedIconArray];
    } else {
        array = [DBUtil query:@"select * from img where grpid=%d", groupID];
    }
    return array;
}

+ (NSArray*)imageArrayForGroupID:(int)groupID startIndex:(int)start count:(int)count
{
    NSArray* array = nil;
    if (groupID == GROUP_KEY_SAVEDICON_ID) {
        array = [self savedIconArrayStartIndex:start count:count];
    } else {
        array = [DBUtil query:@"select * from img where grpid=%d limit %d, %d", groupID, start, count];
    }
    return array;
}

+ (int)imageCountForGroupID:(int)groupID
{
	int count = 0;
	if (groupID == GROUP_KEY_SAVEDICON_ID) {
		NSArray* array = [DBOperation savedIconArray];
		count = (int)array.count;
	} else {
		NSArray* array = [DBUtil query:@"select count(*) as cnt from img where grpid=%d", groupID];
		if (array.count) {
			NSDictionary* dict = [array objectAtIndex:0];
			count = [[dict objectForKey:@"cnt"] intValue];
		}
	}
	return count;
}

+ (NSArray*)imageArrayForImageGridTableViewController:(ImageGridTableViewController*)controller
									imageGridCell:(NImageGridCell*)cell
									  atIndexPath:(NSIndexPath*)indexPath
									withGroupDict:(NSDictionary*)groupDict;
{
	
	NSMutableArray* imageArray = [NSMutableArray array];
	NSNumber* isSavedIcon = [groupDict objectForKey:GROUP_KEY_SAVEDICON];
	NSNumber* groupID = [groupDict objectForKey:GROUP_KEY_ID];
	NSNumber* isDownload = [groupDict objectForKey:GROUP_KEY_DOWNLOAD];
    NSString* groupGlobalPath = [groupDict objectForKey:GROUP_KEY_GLOBALPATH];
	NSArray* imageDictArray = nil;
	
    NSRange imageRange = [controller imageRangeForIndexPath:indexPath];
    imageDictArray = [DBOperation imageArrayForGroupID:groupID.intValue startIndex:(int)imageRange.location count:(int)imageRange.length];
	
	if (isSavedIcon && [isSavedIcon integerValue]) {
		for (NSDictionary* imageDict in imageDictArray) {
			NSString* imagePath = [imageDict objectForKey:@"imagepath"];
			imagePath = [[self savedIconPath] stringByAppendingPathComponent:imagePath];
			
			UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
			if (image) {
				[self setIDToImage:image nid:[imageDict objectForKey:@"id"]];
				[imageArray addObject:image];
			}
		}
	} else {
		BOOL groupNeedDownload = isDownload?[isDownload integerValue]:false;
		NSFileManager* fileManager = [NSFileManager defaultManager];
		
		for (int i=0; i<imageDictArray.count; i++) {
			NSDictionary* imageDict = [imageDictArray objectAtIndex:i];
			NSString* imagePath = [imageDict objectForKey:@"path"];
			UIImage* image = nil;
            BOOL buildInImage = [self isImageBuildIn:imagePath];
			BOOL fileExist = [fileManager fileExistsAtPath:[self getImagePathForPath:imagePath]];
			
			if (imagePath && ![imagePath isEqualToString:@""]) {
                if (!buildInImage) {
                    int indexPathSection = (int)indexPath.section;
                    int indexPathRow = (int)indexPath.row;
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        UIImage* loadedImage = [DBOperation getImageForPath:imagePath];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSIndexPath* curIndexPath = [controller.mtableView indexPathForCell:cell];
                            if (curIndexPath.row == indexPathRow && curIndexPath.section == indexPathSection) {
                                [cell setNewImage:loadedImage forIndex:i];
                            }
                        });
                    });
                    image = [DBOperation defaultIcon];
                } else {
                    image = [DBOperation getImageForPath:imagePath];
                }
                
                
                if ([DBOperation isImageDefaultIcon:imagePath]) {
                    [DBOperation setIDToImage:image nid:DEFAULT_ICON_ID];
                }
                
				[imageArray addObject:image];
			}
			
			if ((buildInImage && groupNeedDownload) || !fileExist) {
				NSString* imageName = [imageDict objectForKey:@"globalname"];
				
				NSString* urlString;
				urlString = [NSString stringWithFormat:@"%@/%@", groupGlobalPath, imageName];
				urlString = UrlEncodePartInString(urlString, @"/");
				urlString = [[NetworkAPI sharedInstance] urlStringForPath:urlString];
				NSURL* theurl = [NSURL URLWithString:urlString];
				
				NSNumber* imageid = [imageDict objectForKey:@"id"];
                int indexPathSection = (int)indexPath.section;
				int indexPathRow = (int)indexPath.row;
				
                [[SDWebImageManager sharedManager] loadImageWithURL:theurl options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                    if (image) {
                        NSString* savePath = [groupGlobalPath stringByAppendingFormat:@"/%@", imageName];
                        NSString* absSavePath = [DocumentDirectory() stringByAppendingFormat:@"/%@", savePath];
                        
                        NSIndexPath* curIndexPath = [controller.mtableView indexPathForCell:cell];
                        if (curIndexPath.row == indexPathRow && curIndexPath.section == indexPathSection) {
                            [cell setNewImage:image forIndex:i];
                        }
                        
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            if (SaveImageToPathCreatePathIfNeed(image, absSavePath)) {
                                [DBUtil update:@"update img set path=%@ where id=%@", savePath, imageid];
                            }
                        });
                    } else {
                        NSLog(@"download %@ error: %@", imageURL, error);
                    }

                }];
//				[[SDWebImageManager sharedManager]
//				 downloadImageWithURL:theurl
//				 options:0
//				 progress:nil
//				 completed:^(UIImage *nimage, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//					 if (nimage) {
//						 NSString* savePath = [groupGlobalPath stringByAppendingFormat:@"/%@", imageName];
//						 NSString* absSavePath = [DocumentDirectory() stringByAppendingFormat:@"/%@", savePath];
//						 
//						 NSIndexPath* curIndexPath = [controller.mtableView indexPathForCell:cell];
//						 if (curIndexPath.row == indexPathRow && curIndexPath.section == indexPathSection) {
//							 [cell setNewImage:nimage forIndex:i];
//						 }
//						 
//                         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                             if (SaveImageToPathCreatePathIfNeed(nimage, absSavePath)) {
//                                 [DBUtil update:@"update img set path=%@ where id=%@", savePath, imageid];
//                             }
//                         });
//					 } else {
//						 NSLog(@"download %@ error: %@", imageURL, error);
//					 }
//				 }];
			}
		}
	}
	
	return imageArray;
}

+ (NSString*)getLocalizedGroupNameFromDict:(NSDictionary*)dict
{
	NSString* title = nil;
    NSString* nameConent = [dict objectForKey:@"name"];
    NSDictionary* nameDict = nil;
    if (nameConent) {
        nameDict = [nameConent objectFromJSONString];
    } else {
        nameDict = [NSDictionary dictionary];
    }
    
	if (IsLanguageSimpleChinese()) {
		title = [nameDict objectForKey:@"cn"];
	} else {
		title = [nameDict objectForKey:@"en"];
	}
	return title;
}

+ (BOOL)isImageBuildIn:(NSString*)imagePath
{
	if (!imagePath) {
		return true;
	}
	
	NSRange range = [imagePath rangeOfString:@":"];
	if (range.location == 0) {
		return true;
	} else {
		return false;
	}
}

+ (UIImage*)defaultIcon
{
	UIImage* image = [UIImage imageNamed:@"default_icon.png"];
	return image;
}

+ (BOOL)isImageDefaultIcon:(NSString*)imagePath
{
	if (!imagePath) {
		return true;
	}
	
    BOOL result = [imagePath isEqualToString:@":default_icon.png"];
    return result;
}

+ (NSString*)getImagePathForPath:(NSString*)path 
{
	NSString* imagePath = nil;
	NSRange range = [path rangeOfString:@":"];
	if (range.location == 0) {
		imagePath = [[NSBundle mainBundle] pathForResource:[path substringFromIndex:1] ofType:nil];
	} else {
		imagePath = [DocumentDirectory() stringByAppendingPathComponent:path];
	}
	
	return imagePath;
}

+ (UIImage*)getImageForPath:(NSString*)path
{
	UIImage* image = nil;
	NSRange range = [path rangeOfString:@":"];
	if (range.location == 0) {
		image = [UIImage imageNamed:[path substringFromIndex:1]];
	} else {
    	NSString* imagePath = [self getImagePathForPath:path];
		image = [DBOperation getImageFromCacheWithKey:imagePath];
		if (!image) {
    		image = [UIImage imageWithContentsOfFile:imagePath];
			if (image) {
				[DBOperation addImageToCache:image withKey:imagePath];
			}
		}
	}
	return image;
}

+ (void)getCoverImageForGroupDict:(NSDictionary*)groupDict asyncBlock:(void(^)(UIImage* image))block {
	if(!groupDict) {
		if (block) {
			block(nil);
		}
		return;
	}
	
	NSString* groupPath = [groupDict objectForKey:GROUP_KEY_GLOBALPATH];
	if (!groupPath || [groupPath isKindOfClass:[NSNull class]]) {
		if (block) {
			block(nil);
		}
		return;
	}
	
	NSString* savePath = [groupPath stringByAppendingFormat:@"/%@", @"cover.png"];
	NSString* absSavePath = [DocumentDirectory() stringByAppendingFormat:@"/%@", savePath];
	NSURL* imageUrl = [DBOperation urlForGroupPath:groupPath imageName:@"cover.png"];
	
	UIImage* image = [DBOperation getImageForPath:savePath];
	if (image) {
		if (block) {
			block(image);
		}
		return;
	}
    [[SDWebImageManager sharedManager] loadImageWithURL:imageUrl options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (image) {
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                if (SaveImageToPathCreatePathIfNeed(image, absSavePath)) {
                }
            });
        } else {
            NSLog(@"download %@ error: %@", imageURL,error);
        }
        
        if (block) {
            block(image);
        }
    }];
//	[[SDWebImageManager sharedManager]
//	 downloadImageWithURL:imageUrl
//	 options:0
//	 progress:nil
//	 completed:^(UIImage *nimage, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//		 if (nimage) {
//			 
//			 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//				 if (SaveImageToPathCreatePathIfNeed(nimage, absSavePath)) {
//				 }
//			 });
//		 } else {
//			 NSLog(@"download %@ error: %@", imageURL,error);
//		 }
//		 
//		 if (block) {
//			 block(nimage);
//		 }
//	 }];
}

+ (void)getImageForImageDict:(NSDictionary*)imageDict
				 ofGroupDict:(NSDictionary*)groupDict
				  asyncBlock:(void (^)(UIImage*))block {
	if (!imageDict || !groupDict) {
		return;
	}
	
	if ([[imageDict objectForKey:@"grpid"] integerValue] != [[groupDict objectForKey:@"id"] integerValue]) {
		NSLog(@"image dic and group dict not match");
		return;
	}
	
	BOOL needDownload = [[groupDict objectForKey:@"downloaded"] integerValue];
	NSString* imagePath = [imageDict objectForKey:@"path"];
	
	if (needDownload && [DBOperation isImageBuildIn:imagePath]) {
		
		NSString* groupPath = [groupDict objectForKey:@"globalpath"];
		NSString* imageName = [imageDict objectForKey:@"globalname"];
		NSURL* imageUrl = [DBOperation urlForGroupPath:groupPath imageName:imageName];
		NSNumber* imageid = [imageDict objectForKey:@"id"];
		
		if (block) {
			UIImage* image = [DBOperation getImageForPath:[imageDict objectForKey:@"path"]];
			block(image);
		}
        [[SDWebImageManager sharedManager] loadImageWithURL:imageUrl options:0 progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            if (image) {
                NSString* savePath = [groupPath stringByAppendingFormat:@"/%@", imageName];
                NSString* absSavePath = [DocumentDirectory() stringByAppendingFormat:@"/%@", savePath];
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    if (SaveImageToPathCreatePathIfNeed(image, absSavePath)) {
                        [DBUtil update:@"update img set path=%@ where id=%@", savePath, imageid];
                        [imageDict setValue:savePath forKey:@"path"];
                    }
                });
            } else {
                NSLog(@"download %@ error: %@", imageURL, error);
            }
            
            if (block) {
                block(image);
            }

        }];
//		[[SDWebImageManager sharedManager]
//		 downloadImageWithURL:imageUrl
//		 options:0
//		 progress:nil
//		 completed:^(UIImage *nimage, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//			 if (nimage) {
//				 NSString* savePath = [groupPath stringByAppendingFormat:@"/%@", imageName];
//				 NSString* absSavePath = [DocumentDirectory() stringByAppendingFormat:@"/%@", savePath];
//				 
//				 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//					 if (SaveImageToPathCreatePathIfNeed(nimage, absSavePath)) {
//						 [DBUtil update:@"update img set path=%@ where id=%@", savePath, imageid];
//						 [imageDict setValue:savePath forKey:@"path"];
//					 }
//				 });
//			 } else {
//				 NSLog(@"download %@ error: %@", imageURL, error);
//			 }
//			 
//			 if (block) {
//				 block(nimage);
//			 }
//		 }];
	} else {
		if (block) {
			UIImage* image = [DBOperation getImageForPath:[imageDict objectForKey:@"path"]];
			block(image);
		}
	}
}

+ (void)setIDToImage:(UIImage *)image nid:(NSNumber *)nid
{
	objc_setAssociatedObject(image, &id_key, nid, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (int)getIDFromImage:(UIImage *)image
{
	int rid = -1;
	id assocatidObject = objc_getAssociatedObject(image, &id_key);
	if (assocatidObject) {
		rid = (int)[assocatidObject integerValue];
	}
	return rid;
}

+ (NSString *)admobID
{
	NSString* theid = @"ca-app-pub-8324715366985508/9209062277";
	NSArray* result = [DBUtil query:@"select * from cfg where `key`='admob_id'"];
	if (result.count) {
		theid = [[result objectAtIndex:0] objectForKey:@"value"];
	}
	return theid;
}

+ (NSString *)admobPageID
{
	NSString* theid = @"ca-app-pub-8324715366985508/1491405079";
	NSArray* result = [DBUtil query:@"select * from cfg where `key`='admob_page_id'"];
	if (result.count) {
		theid = [[result objectAtIndex:0] objectForKey:@"value"];
	}
	return theid;
}

+ (void)addImageToCache:(UIImage*)image withKey:(NSString*)key
{
	static dispatch_once_t oneceToken;
	dispatch_once(&oneceToken, ^{
		imageCacheDict = [NSMutableDictionary dictionary];
	});
	
#if IMAGE_CACHE_THREAD_SAFE
	@synchronized(self) {
#endif
		if (image) {
			[imageCacheDict setObject:image forKey:key];
		}
#if IMAGE_CACHE_THREAD_SAFE
	}
#endif
}

+ (UIImage*)getImageFromCacheWithKey:(NSString*)key
{
	UIImage* image = nil;
	if (key) {
#if IMAGE_CACHE_THREAD_SAFE
	@synchronized(self) {
#endif
			image = [imageCacheDict objectForKey:key];
#if IMAGE_CACHE_THREAD_SAFE
	}
#endif
	}
	return image;
}

+ (void)clearCache
{
#if IMAGE_CACHE_THREAD_SAFE
	@synchronized(self) {
#endif
		[imageCacheDict removeAllObjects];
#if IMAGE_CACHE_THREAD_SAFE
	}
#endif
}

+ (NSString*)baseUrl
{
	NSString* url = DEFAULT_URL;
	@try {
		NSArray* result = [DBUtil query:@"select key, value from cfg where key='base_url'"];
		if (result.count) {
			NSDictionary* dict = [result objectAtIndex:0];
			url = [dict objectForKey:@"value"]?[dict objectForKey:@"value"]:DEFAULT_URL;
		}
	}
	@catch(...) {
		
	}
	return url;
}

+ (NSURL*)urlForGroupPath:(NSString*)groupPath imageName:(NSString*)imageName
{
	NSString* urlString;
	urlString = [NSString stringWithFormat:@"%@/%@", groupPath, imageName];
	urlString = UrlEncodePartInString(urlString, @"/");
	urlString = [[NetworkAPI sharedInstance] urlStringForPath:urlString];
	NSURL* theurl = [NSURL URLWithString:urlString];
	
	return theurl;
}

+ (BOOL)BoolValueForKey:(NSString*)key default:(BOOL)defaultValue
{
    BOOL resultValue = defaultValue;
	@try {
		NSArray* result = [DBUtil query:@"select key, value from cfg where key=%@", key];
		if (result.count) {
			NSDictionary* dict = [result objectAtIndex:0];
			resultValue = [dict objectForKey:@"value"]?[[dict objectForKey:@"value"] boolValue]:false;
		}
	}
	@catch(...) {
		
	}
	
	return resultValue;
}

+ (BOOL)isAppListEnabled
{
	BOOL enalbed = false;
    enalbed = [self BoolValueForKey:@"app_list_enabled" default:false];
	
	return enalbed;
}

+ (BOOL)isRate2UnlockEnabled
{
	BOOL enalbed = false;
    enalbed = [self BoolValueForKey:@"rate_unlock_enabled" default:false];
	
	return enalbed;
}

+ (BOOL)isUserRated
{
    BOOL rated = false;
    rated = [self BoolValueForKey:@"user_rated" default:false];
    return rated;
}

+ (void)setRate2UnlockEnable:(BOOL)enabled
{
    [DBUtil update:@"insert or replace into cfg(key, value) values(%@, %@)", @"rate_unlock_enabled", enabled?@"1":@"0"];
}

+ (void)setUserRated:(BOOL)rated
{
    [DBUtil update:@"insert or replace into cfg(key, value) values(%@, %@)", @"user_rated", rated?@"1":@"0"];
}

+ (NSArray *)myAppIdList
{
    NSString* key = @"my_app_id_list";
    NSArray* result = [DBUtil query:@"select key, value from cfg where key=%@", key];
    /*
     673530545 : Screen Icon Free
     663420081 : Screen Icon
     622069798 : Photo Shift
     1020645701: Happy Gomoku
     1094172428: Rect Match
     1120137109: Photo Title
     1084229314: Chinese Chess Ace
     1074547374: Sudoku Ace
     1063025331: Hex Me
     */
    NSString* appids = result&&result.count?[[result objectAtIndex:0] objectForKey:@"value"]:@"673530545,663420081,622069798,1020645701,1094172428,1120137109,1084229314,1074547374,1063025331";
    NSArray* appidArray = [appids componentsSeparatedByString:@","];
    
    return appidArray;
}

@end
